package com.tnovoselec.android.travelassistant.async;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.concurrent.Callable;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import android.content.Context;
import android.util.Log;

import com.nth.android.Util;
import com.tnovoselec.android.travelassistant.dto.MeteoFavoritesDto;
import com.tnovoselec.android.travelassistant.dto.MeteoResultHolder;
import com.tnovoselec.android.travelassistant.parser.MeteoParser;


/**
 * Title: Android Framework - FeedHandler <br />
 * Copyright: Copyright (c) 2011 <br />
 * NTH Company: NTH d.o.o. <br />
 * 
 * @author Tomislav Novoselec
 * @version 1.0.0
 * @since 1.0.0
 * 
 *        DownloadWeather class is used to asynchronously download and parse the
 *        XML containing all weather data will be shown in app. It also caches
 *        them in application's file directory.
 */
public class DownloadWeather implements Callable<Boolean> {

	public static long CACHE_VALIDITY = 15 * 60 * 1000;

	private final String TAG = DownloadWeather.class.getSimpleName();

	private String xmlUrl;
	private Context context;
	private boolean fromCache;

	public DownloadWeather(String xmlUrl, Context context, boolean fromCache) {
		super();
		this.xmlUrl = xmlUrl;
		this.context = context;
		this.fromCache = fromCache;
	}

	@Override
	public synchronized Boolean call() throws Exception {
		Log.i("Downloading weather", "");
		HttpURLConnection connection = null;
		InputStream is = null;

		try {
			if (Util.fileExistsHex(xmlUrl, context) && (System.currentTimeMillis() - Util.getFileHex(xmlUrl, context).lastModified()) < CACHE_VALIDITY) {
				// is = Util.readFile(xmlUrl, context);
			} else if (!fromCache) {
				// TODO ubaciti u Util framework
				URL imageUrl = new URL(xmlUrl);
				connection = (HttpURLConnection) imageUrl.openConnection();
				connection.setConnectTimeout(Util.HTTP_CONNECT_TIMEOUT);
				connection.setReadTimeout(Util.HTTP_READ_TIMEOUT);
				connection.setDoInput(true);
				connection.connect();

				is = connection.getInputStream();
				Util.fileCreate(xmlUrl, is, context);
			}
			if (Util.fileExistsHex(xmlUrl, context)) {
				is = Util.readFile(xmlUrl, context);
			} else {
				return Boolean.FALSE;
			}
			MeteoParser parser = new MeteoParser();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser sp = factory.newSAXParser();
			sp.parse(is, parser);

			final List<MeteoFavoritesDto> items = parser.getWeathers();
			MeteoResultHolder.init(items);

		} catch (Exception ex) {
			Log.e(TAG, ex.getMessage(), ex);
			return Boolean.FALSE;
		}
		return Boolean.TRUE;
	}

}
